<?php


namespace app\cms\model\saas;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class saasClientServerModel extends QueryModel
{
    const isSaasModel = true;
    protected $table = 'saas_client_server_table';


    public function getInfoById(int $server_id): array
    {
        $server = $this->where([
            'server_id' => $server_id
        ]) -> findOrEmpty();
        return $server -> isEmpty() ? [] : $server -> toArray();
    }

    public function getSaasClientServerList(
      string $server_name = '',
      string $server_ip = '',
      int $status = -1
    ): Response {
        $where = [];
        if ($server_name !== '') {
            $where[] = [
                'server_name', 'like', "%${server_name}%"
            ];
        }

        if ($server_ip) {
            $where[] = [
                'server_ip', 'like', "%{$server_ip}%"
            ];
        }

        if ($status > -1) {
            $where[] = [
                'status', '=', $status
            ];
        }

        return $this->paginateQuery(
            $this->where($where)
        );
    }

    /**
     * 添加saas服务器
     * @param string $server_name
     * @param string $server_ip
     * @param int $server_port
     * @param int $status
     * @return Response
     */
    public function addSaasServer(
        string $server_name,
        string $server_ip,
        int $server_port,
        int $status = 0
    ): Response {

        $exists = $this->where([
            'server_name' => $server_name
        ]) -> findOrEmpty();

        // 存在当前名称即重置
        if ($exists -> isExists()) {
//            $server_name = uniqid("{$server_name}_");
            return message() -> parameter_error('服务器名称已存在');
        }

        return $this->createData([
            'server_name' => $server_name,
            'server_ip' => $server_ip,
            'server_port' => $server_port,
            'status' => $status
        ]);
    }

    /**
     * 更新Saas服务器
     * @param int $server_id
     * @param string $server_name
     * @param string $server_ip
     * @param int $status
     * @return Response
     */
    public function updateSaasServer(
        int $server_id, string $server_name, string $server_ip, int $status
    ): Response {

        $update = [
            'server_name' => $server_name,
            'server_ip' => $server_ip
        ];

        if ($status > -1) $update['status'] = $status;
        return $this->updateInfo($update, [
            'server_id' => $server_id
        ]);
    }
}